package threads;
/*模拟老板写订单，员工是不能看的，员工看订单的时候，老板是不能写的*/
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//可重入读写锁实列
public class ReentrantReadWriteLockExample {
    //定义一个全局可重入锁
    private static final ReentrantReadWriteLock orderLock=new ReentrantReadWriteLock();
    public static void main(String [] args) throws InterruptedException {
        handOrder();
        Thread t=new Thread();
        t.start();

    }
    public static void handOrder()throws InterruptedException
    {
        //模拟买奶茶的方法
        final ReentrantReadWriteLockExample rrw=new ReentrantReadWriteLockExample();
        Thread boos=new Thread(new Runnable() {
            @Override
            public void run() {
                while(true)
                {
                    try {
                        rrw.addOrder();
                        Thread.sleep((long)(Math.random())*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        });
    }
    public void addOrder() throws InterruptedException
    {
        //模拟老板添加订单的方法
        //利用可重入的读写锁来写订单
        orderLock.writeLock().lock();//锁住不让其他资源占领
        long writeTime=(long)(Math.random()*1000);
        Thread.sleep(writeTime);
        System.out.println("老板添加一笔订单");
        orderLock.writeLock().unlock();//释放订单锁

    }
    public void viewOrder()throws InterruptedException
    {
        //员工查看订单
        orderLock.readLock().lock();
        long readTime=(long)(Math.random()*1000);
        Thread.sleep(readTime);
        System.out.println(Thread.currentThread().getName()+":查看了订单");
        orderLock.readLock().unlock();//读完之后要释放锁
    }

}
